import htmlparse from '@/common/html-parser.js'
import {
	uniUploadFile
} from '@/common/promise.js'
import {
	img_path,HTTP_REQUEST_URL,HOST
} from '@/config.js'
// 获取页面栈 delta = n-1
const getCurrenPage = (n) => {
	let pages = getCurrentPages();
	let targetPage = pages[pages.length - n];
	return targetPage
}

 

/*
 *   时间戳转格式
 *   
 *
 **/ 
const dateFormat = (timestamp, format)=> {
      if (String(timestamp).length === 10) {
        timestamp = timestamp * 1000
      }
      var date = new Date(timestamp)
      var Y = date.getFullYear()
      var M = date.getMonth() + 1
      var D = date.getDate()
      var hour = date.getHours()
      var min = date.getMinutes()
      var sec = date.getSeconds()
      if (format === 'YYYY') {
        return Y // 2021
      } else if (format === 'YYYY-MM') { // 2021-07
        return Y + '-' + (M < 10 ? '0' + M : M)
      } else if (format === 'YYYY-MM-DD') { // 2021-07-12
        return Y + '-' + (M < 10 ? '0' + M : M) + '-' + (D < 10 ? '0' + D : D)
      } else if (format === 'HH:mm:ss') { // 10:20:35
        return (hour < 10 ? '0' + hour : hour) + ':' + (min < 10 ? '0' + min : min) + ':' + (sec < 10 ? '0' + sec : sec)
      } else if (format === 'YYYY-MM-DD HH:mm') { // 2021-07-12 10:20
        return Y + '-' + (M < 10 ? '0' + M : M) + '-' + (D < 10 ? '0' + D : D) + ' ' + (hour < 10 ? '0' + hour : hour) + ':' + (min < 10 ? '0' + min : min)
      } else if (format === 'YYYY-MM-DD HH:mm:ss') { // 2021-07-12 10:20:35
        return Y + '-' + (M < 10 ? '0' + M : M) + '-' + (D < 10 ? '0' + D : D) + ' ' + (hour < 10 ? '0' + hour : hour) + ':' + (min < 10 ? '0' + min : min) + ':' + (sec < 10 ? '0' + sec : sec)
      } else {
        return '--'
      }
}

// 坐标转换 度分秒格式
const d2Dms = (data) => {
  let d = parseInt(data);
  let m = parseInt((data - d) * 60);
  let s = Math.floor(((data - d) * 60 - m) * 60 * 100) / 100;
  return d + "°" + m + "′" + s + "″";
}

// 解析html 转 数组
const htmlParse = (html) => {
	let htmlNodes = [];
	let htmlString = '';

	htmlString = html.replace(/<p([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, '<p') 
		.replace(/<p>/ig, '<p class="html_p">')
		.replace(/<br>/ig, '<p class="html_p">')
		.replace(/<div>/ig, '<div class="html_p">')
		.replace(/<img/ig, '<img class="html_img"') 
		.replace(/<video/ig, '<video class="html_video"')  
		.replace(/\/api/ig, HOST+'\/api') 
	console.log('htmlString',htmlString)
	// htmlNodes = htmlparse(htmlString); 
	return htmlString;
}
 

/*  
 * 参数复杂路由跳转传入（object）
 * opentype:'navigate',   跳转方式 跟opentype
 * backOpenType:'navigate', 回跳方式
 * url:'/pages/member/group/group',     // 目标url
 * backurl:'',       返回路由
 * params:{type:'select',memberid:this.member.select},  	  // 目标url参数 * 
 * backparams:{type:'select',memberid:[]},   返回路由参数
 *   
 *  /pages/login/login?id=1&type=add&backurl=%%%%%%%%%%%%5
 */
const router = (data) => {
	let targetUrl = '',
		url = '',
		urlQuery = '',
		params = '',
		backUrl = '',
		backUrlParams = '',
		urlParams = '', // eg 'pages/login/login?type=a' 
		backOpenType = '';

	// 处理目标url
	// 1 判断是否带url参数
	if (data.url.indexOf('?') != -1) {
		data.url = data.url.split('?');
		url = data.url[0];
		urlQuery = data.url[1];
		params = urlQuery;
	} else {
		url = data.url;
	}

	// 处理参数
	if (data.params) {
		for (let i in data.params) {
			if (typeof(data.params[i]) == 'object') { // 处理参数值为对象时转码
				data.params[i] = objectToEncode(data.params[i])
			}
		}
		if (urlQuery) {
			params = urlQuery + '&' + jsonToQuery(data.params);
		} else {
			params = jsonToQuery(data.params);
		}
	}

	if (data.backurl) {
		if (data.backOpenType) {
			backOpenType = "&backOpenType=" + data.backOpenType;
		}
		// 回传参数
		//1 判断url是否带参数   /pages/login/login?a=1&b=2
		if (data.backurl.indexOf('?') != -1) {
			data.backurl = data.backurl.split('?')
			backUrl = data.backurl[0];
			urlParams = data.backurl[1];
			backUrlParams = urlParams;
		} else {
			backUrl = data.backurl;
		}

		if (params) {
			backUrl = "&backurl=" + backUrl;
		} else {
			backUrl = "?backurl=" + backUrl;
		}

		if (data.backparams) {
			if (backUrlParams) {
				backUrlParams = backUrlParams + '&' + jsonToQuery(data.backparams)
			} else {
				backUrlParams = jsonToQuery(data.backparams)
			}
		}
		if (backUrlParams) {
			backUrlParams = "&backparams=" + objectToEncode(backUrlParams)
		}
	}

	targetUrl = url + '?' + params + backUrl + backUrlParams + backOpenType;
	switch (data.opentype) {
		case 'navigate':
			uni.navigateTo({
				url: targetUrl,
			});
			break;
		case 'redirect':
			uni.redirectTo({
				url: targetUrl,
			});
			break;
		case 'switchTab':
			uni.redirectTo({
				url: targetUrl,
			});
			break;
		case 'reLaunch':
			uni.reLaunch({
				url: targetUrl,
			});
			break;
	}
}



/*
 * 字符串转码
 * "xxxxx"=>%7B%22id%22%3A1%7D
 * */
const queryToEncode = (data) => {
	let enCode = encodeURIComponent(data);
	return enCode
}

/*
 * 字符串解码
 * %7B%22id%22%3A1%7D=>"xxxxx"
 * */
const encodeToString = (data) => {
	let str = decodeURIComponent(data);
	return str
}

/*
 * 	url参数转对象  
 * 	eg: type=2&ca_id=1  => {type:2,ca_id:1}
 * 		[type=2,ca_id=1] => [[type,2],[ca_id,1]] =>	{type:2,ca_id:1}
 * */
const queryToJSON = (str) => {
	let query = [],
		data = {};
	let query_arr = str.split('&');
	query_arr.forEach(item => {
		let query_item = item.split('=');
		query.push(query_item)
	})
	query.forEach(item => {
		data[item[0]] = item[1]
	})
	return data
}

/*
 * json转化成url参数
 *  eg:{a:1,b:2} =  a=1&b=2
 * 
 * ***/
const jsonToQuery = (data) => {
	let jsonStr = JSON.stringify(data);
	let query = '';
	let reg1 = /[{}"]/ig; // 去掉{}"
	let reg2 = /[:]/ig; // 匹配全部:
	let reg3 = /[,]/ig; // 匹配全部,
	query = jsonStr.replace(reg1, "") // 去掉{}"
		.replace(reg2, "=") // =替换:
		.replace(reg3, "&"); // &替换,          
	return query;
}


// 检查手机号 
const checkPhone = (data) => {
	let phoneReg = /^1[2|3|4|5|6|7|8|9][0-9]{9}$/;
	if (!phoneReg.test(data)) {
		return false
	} else { 
		return true
	}
}

// 检测身份证号等
const checkIdCard = (data) => {
	let cardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
	if (!cardReg.test(data)) { 
		return false
	} else { 
		return true
	}
}

// 替换字符串指定位置* （手机号/身份证号）
const replaceStr = (str, index, changeStr) => {
	return str.substr(0, index) + changeStr + str.substr(index + changeStr.length);
}

// 阻止按钮快速点击事件
const stop = function stopClickEvent(fn) {
	let that = this;
	if (that.isStop) {
		that.isStop = false;
		fn();
	} else { 
	}
}
 

/*
 *  
 * count:最多上传图片数量，最多9张
 * len:已上传数量
 * success:成功回调
 * 
 * */
const uploadImage = (data) => {
	let _this = this;
	let imgUrl = [],
		uploadNum = data.length,
		count = 9,
		callback = data.success,
		sourceType=[];

	if (data.maxSize && data.maxSize <= 9) {
		count = data.maxSize;
	}
	if(data.sourceType){
		sourceType=data.sourceType;
	}else{
		sourceType=['album', 'camera'];
	}

	count = count - uploadNum; // 计算剩余可上传数量

	uni.chooseImage({
		count: count, //默认9
		sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
		sourceType: sourceType, //从相册选择
		success: function(res) { 
			return callback(res)
		}
	})
}


/*
 *  预览图片
 *  data.data  预览图片 数组
 *  data.index 第几张开始预览
 * */
const previewImage = (data) => { 
	let img = data.data,
		index = data.index;
	uni.previewImage({
		current: index,
		urls: img,
		loop: true,
		indicator: "number"
	})
}

/*
 *  上传文件到服务器 
 *  data.url 服务器接口
 *  data.filePath 图片本地临时地址
 *  data.name 目录名称
 *  data.formData 其他参数
 * 
 * */
const uploadToServe = (data) => {  
	console.log('uploadToServe',data)
	let callback = data.success;
	return new Promise((resolve, reject) => {
		uniUploadFile({ 
			url: data.url,
			filePath: data.filePath,
			name: data.name,
			formData: data.formData
		}).then((up_res) => {     
			console.log(up_res)
			if(up_res.statusCode==200){
				let up_res_data = decodeURIComponent(up_res.data);
				up_res_data = up_res_data.replace(/[\\]/g, '');
				up_res_data = JSON.parse(up_res_data);
				
				resolve(up_res_data)
			}
		}).catch((err) => { 
			reject(err)
		})
	})
}
 

/*
 * 图片原图路径  
 * */
const imgPath=(path)=>{	
	return HTTP_REQUEST_URL+'/image/image?path='+path;
} 

/*
 *  图片缩略图路径  
 * 
 * */
const smallPath=(path)=>{	
	return HTTP_REQUEST_URL+'/image/compress?from=zdy_base&path='+path+'&isgd=1&width=200';
} 

/*
 *  金额千分位转化
 *  原理    金额整数部分转化数组 倒序处理    eg   715600.56=>[0,0,6,5,1,7]
 * 	        %3==0时，添加“,”巷
 *
 **/ 
const moneyToFormat=(data)=>{ 	
	if(data==0 || !data){
		return 0
	}
	let price_data='';
	if(typeof(data)=='string'){
		price_data=data;
	}else{
		price_data=JSON.stringify(data); 
	}
	 
	let data_arr=price_data.split('.'); 
	let integer=data_arr[0].split('').reverse(); 
	let decimal=data_arr[1]; 
	let arr=[];
	let money='';
	for(let i=0;i<integer.length;i++){
		arr.push(integer[i]);
		if((i+1)%3==0 && (i+1)!=integer.length){
			arr.push(',');
		}
	} 
	if(decimal){
		money=arr.reverse().join('')+'.'+decimal; 
	}else{
		money=arr.reverse().join(''); 
	}
	
	return money
}
// 获取文件类型
const checkFileType = (str) => { 
	let data=str.split('.');
	let type=''; 
	if(data[data.length-1]=='doc'||data[data.length-1]=='docx'){
		type=1;
	}
	if(data[data.length-1]=='xls'||data[data.length-1]=='xlsx'){
		type=2;
	}
	if(data[data.length-1]=='pdf'){
		type=3;
	}
	if(data[data.length-1]=='jpg'||data[data.length-1]=='png'||data[data.length-1]=='jpeg'){
		type=4;
	}
	if(data[data.length-1]=='txt'){
		type=5;
	}
	if(data[data.length-1]=='rar'){
		type=6;
	}
	return type
}

export {
	getCurrenPage,
	htmlParse,
	router,
	checkPhone,
	stop,
	checkIdCard,
	queryToEncode,
	queryToJSON,
	encodeToString,
	uploadImage,
	previewImage,
	jsonToQuery,
	replaceStr,
	dateFormat,
	uploadToServe, 
	d2Dms,
	imgPath,
	smallPath,
	moneyToFormat,
	checkFileType


}
